﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CSharpThreadLifeCycle
{
    /// <summary>
    /// 
    /// 【1】启动：让线程运行
    /// 【2】暂停：线程暂时停止运行
    /// 【3】继续：从线程暂停的地方、继续执行
    /// 【4】中断：线程运行中，突然“打断”一次（必须在运行状态才可以）。（一般不使用）
    /// 【5】终止：当前正在运行的线程，直接停止，不在运行，线程只有终止才能关闭窗体！！
    /// 
    /// 
    /// </summary>
    public partial class FrmThread : Form
    {
        public FrmThread()
        {
            InitializeComponent();
        }

        private Thread thread = null;
        private int counter = 0;

        //手动创建一个事件通知对象
        private ManualResetEvent mResetEvent = new ManualResetEvent(true); 

        //启动
        private void btn_Start_Click(object sender, EventArgs e)
        {
            thread = new Thread(() =>
            {
                while (true)
                {
                    try
                    {
                        Thread.Sleep(500);

                        mResetEvent.WaitOne();  //用来判断是否要“暂停”或“继续”线程的运行

                        this.Invoke(new Action(() =>
                        {
                            this.lblInfo.Text += counter++ + ",";
                        }));
                    }
                    catch(Exception ex)
                    {
                        MessageBox.Show(ex.Message + "异常位置：" + counter++);
                    }
                }
            });
            thread.Start();
        }

        //暂停
        private void btnReset_Click(object sender, EventArgs e)
        {
            if(thread.ThreadState == ThreadState.WaitSleepJoin)
            {
                mResetEvent.Reset();
            }
        }

        //继续
        private void btnSet_Click(object sender, EventArgs e)
        {
            if (thread.ThreadState == ThreadState.WaitSleepJoin)
            {
                mResetEvent.Set();
            }
        }

        //中断
        private void btnInterrupt_Click(object sender, EventArgs e)
        {
            thread.Interrupt();
        }

        //终止  
        private void btnAbort_Click(object sender, EventArgs e)
        {
            thread.Abort();
        }

        private void btnJoin_Click(object sender, EventArgs e)
        {
            Thread thread = new Thread(() =>
            {
                Thread.Sleep(3000);
                Console.WriteLine("子线程任务处理完毕");
            });
            thread.Start();

            thread.Join(); //主线程会等待子线程执行完毕后，再执行

            Console.WriteLine("主线程任务处理完毕");
        }
    }
}
